package com.aaa.config;

import com.aaa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description: TODO
 * @date 2023/1/3
 */
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Autowired
    private UserService userService;
    //指定账号和密码的来源
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
    //设置security认证的规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //这顶登录表单的规则
        http.formLogin()
                //这个路径必须和登录表单的提交路径一致
                .loginProcessingUrl("/login")
                //自定义登录页面
                .loginPage("/login.html")
                //登录成功后转发的路径
                .successForwardUrl("/main")
                .permitAll();

        //没有权限时跳转的路径
        http.exceptionHandling().accessDeniedPage("/403.html");
        //禁用跨站伪造请求--相当于不使用csrf过滤器
        http.csrf().disable();
        //设置其他路径需要认证后才能访问
        http.authorizeRequests().anyRequest().authenticated();
    }
}
